package com.sz.sendmsg.realm;

import com.sz.sendmsg.entity.Manager;
import com.sz.sendmsg.service.ShiroService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    ShiroService shiroService;
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Manager user = (Manager) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        /**
         * 授权
         * setRoles 授予该用户是什么角色
         * setStringPermissions 授予改用户的操作权限
         */
        simpleAuthorizationInfo.setRoles(shiroService.getRolesById(user.getManagerId()));
        simpleAuthorizationInfo.setStringPermissions(shiroService.getPermsissionById(user.getManagerId()));
        return simpleAuthorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        String credentials = new String((char[])token.getCredentials());
        Manager user = shiroService.getManager(principal);
        if(user !=null && user.getLoginName().equals(principal) && user.getPassword().equals(credentials)){
            return new SimpleAuthenticationInfo(user,credentials,this.getName());
        }
        return null;
    }
}
